package net.csdn.business.common.config;

import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import lombok.extern.slf4j.Slf4j;
import net.csdn.business.common.enums.ResultCodeEnum;
import net.csdn.business.common.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.StopWatch;

import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * @ClassName EncryptUtil
 * @Description webHook加解密工具类
 * @Author zhangyl
 * @Date 2023/4/26 14:19
 */
@Slf4j
public class EncryptUtil {

    /**
     * @Author zhangyl
     * @Description webHook配置敏感字段使用aes的CBC模式加密方法
     * @Date 11:21 2023/5/7
     * @Param
     * @return
     **/
    public static String encryptString(String data, String iv, String key){
        if(StringUtils.isBlank(data)){
            return null;
        }
        if(StringUtils.isBlank(key)){
            throw new BusinessException(ResultCodeEnum.ENCRYPT_KEY_ERROR);
        }
        if(StringUtils.isBlank(iv)){
            throw new BusinessException(ResultCodeEnum.ENCRYPT_IV_ERROR);
        }
        log.info("encryptUrlIv is :{}",iv);
        StopWatch sw = new StopWatch();
        sw.start("encrypt string");
        AES aes= new AES(Mode.CBC, Padding.ZeroPadding,
                    new SecretKeySpec(key.getBytes(), "AES"),
                    new IvParameterSpec(iv.getBytes()));
        String res=aes.encryptBase64(data, StandardCharsets.UTF_8);
        sw.stop();
        log.info("{} time is：{}ms", sw.getLastTaskName(), sw.getLastTaskTimeMillis());
        log.info("encrypt res is: {}",res);
        return res;
    }

    /**
     * @Author zhangyl
     * @Description webHook配置敏感字段使用aes的CBC模式解密方法
     * @Date 11:21 2023/5/7
     * @Param
     * @return
     **/
    public static String decryptString(String data, String iv, String key){
        if(StringUtils.isBlank(data)){
            return null;
        }
        if(StringUtils.isBlank(key)){
            throw new BusinessException(ResultCodeEnum.ENCRYPT_KEY_ERROR);
        }
        if(StringUtils.isBlank(iv)){
            throw new BusinessException(ResultCodeEnum.ENCRYPT_IV_ERROR);
        }
        log.info("encryptUrlIv is :{}",iv);
        StopWatch sw = new StopWatch();
        sw.start("decrypt string");
        AES aes= new AES(Mode.CBC, Padding.ZeroPadding,
                new SecretKeySpec(key.getBytes(), "AES"),
                new IvParameterSpec(iv.getBytes()));
        byte[] decryptDataBase64 = aes.decrypt(data);
        String res=new String(decryptDataBase64, StandardCharsets.UTF_8);
        sw.stop();
        log.info("{} time is：{}ms", sw.getLastTaskName(), sw.getLastTaskTimeMillis());
        log.info("encrypt res is: {}",res);
        return res;
    }
}
